"""
线程的创建：threading
"""
import os
#方法名Thread创建线程
#start启动线程
#join阻塞直到线程执行结束
#getName获取线程名字
#setName设置线程的名字
#is_alive判断线程是否存活
#setDaemon守护线程 setDaemon(True)

import random
import time
import threading

lists = ['python','django','tornado',
         'flask','bs5','requests','uvloop'
]
new_list = []

def work():
    if len(lists) == 0:
        return
    data = random.choice(lists)
    lists.remove(data)
    new_data = f'{data}_new'
    new_list.append(new_data)
    time.sleep(1)

if __name__ == '__main__':
    start = time.time()
    t_list = []
    for i in range(len(lists)):
        t = threading.Thread(target=work)
        t_list.append(t)
        t.start()

    for t in t_list:
        t.join()

    print('old list', lists)
    print('new list', new_list)
    print('time is ', time.time() - start)

"""
线程池：concurrent
"""
# tpool = futures.ThreadPoolExecutor(max_workers)
#submit往线程池中加入任务
#done线程池中的某个线程是否完成了任务
#result获取当前线程执行任务的结果

from concurrent.futures import ThreadPoolExecutor

lock = threading.Lock() #线程加锁放在全局即可，进程要传入到参数中
def work2(i):
    # lock.acquire()
    print(i,os.getpid())
    time.sleep(1)
    # lock.release()
    return f'result is {i}'

if __name__ == '__main__':
    print(os.getpid())
    t = ThreadPoolExecutor(2)
    result = []
    for i in range(20):
        t_result = t.submit(work2,(i,))
        result.append(t_result)

    for res in result:
        print(res.result())